﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Fetches.Fetch.Utils.FileHosting;
using Fetches.Fetch.Utils.KvStore;
using Microsoft.AspNetCore.Http;

namespace FetchesDeploy.ScalableFactory.Middleware
{
    public class FileHostProxy
    {
        static IKvStore _id2Hash = new RedisKvStore();
        static IHostFileProvider hostFileProvider = new LocalFileHosting();
        static HttpClient _http = new HttpClient();

        static FileHostProxy()
        {
            _id2Hash.Initialize("192.168.1.66:6379", 0);
            hostFileProvider.Initialize(@"D:\Deploy\Hosting");
        }

        public static async Task Invoke(HttpContext context)
        {
            var id = context.Request.Query["id"].ToString();
            var hash = _id2Hash.Get(id);

            var rsp = context.Response;
            if (string.IsNullOrEmpty(hash))
            {
                rsp.StatusCode = 404;
            }
            else
            {
                rsp.ContentLength = hostFileProvider.ItemLength(hash);
                await hostFileProvider.Read(hash).CopyToAsync(rsp.Body);
            }


        }

    }
}
